<script lang="ts" setup>
import { ref, nextTick } from "vue"
import TodoHeader from "./components/todo-header/index.vue"
import TodoList from "./components/todo-list/index.vue"
import TodoBottom from "./components/todo-bottom/index.vue"

import type { TodoItem } from "./index"

const todoList = ref<Array<TodoItem>>([])

const isAllCheckedStatus = ref<boolean>(false)

const updateIsAllCheckedStatus = () => {
  isAllCheckedStatus.value = todoList.value.every(todo => todo.isCheck)
}
updateIsAllCheckedStatus()

const addTodo = (todoName: string) => {
  todoList.value.push({
    name: todoName,
    isCheck: false,
  })
  updateIsAllCheckedStatus()
}

const removeTodo = (index: number) => {
  todoList.value = todoList.value.filter((todo, i: number) => i !== index)
  updateIsAllCheckedStatus()
}

const removeAllCheckedTodo = () => {
  todoList.value = todoList.value.filter(todo => !todo.isCheck)
}
const todoCheckStatusChange = async () => {
  await nextTick()
  updateIsAllCheckedStatus()
}
const allCheckStatusChange = () => {
  isAllCheckedStatus.value = !isAllCheckedStatus.value
  todoList.value.forEach(todo => (todo.isCheck = isAllCheckedStatus.value))
}
</script>

<template>
  <div>
    <TodoHeader @addTodoEvent="addTodo" />
    <TodoList
      :todoList="todoList"
      @removeTodoEvent="removeTodo"
      @todoCheckStatusChangeEvent="todoCheckStatusChange"
    />
    <TodoBottom
      :isAllCheckedStatus="isAllCheckedStatus"
      @removeAllCheckedTodoEvent="removeAllCheckedTodo"
      @allCheckStatusChangeEvent="allCheckStatusChange"
      v-show="todoList.length"
    />
  </div>
</template>
